<?php
declare (strict_types = 1);
namespace app\user\logic\user;

use app\common\exception\LogicException;
use app\user\model\user\PunchIn as PunchInModel;

use think\facade\Event;
use app\user\event\subscribes\user\Credit as CreditEvent;

/**
 * 签到接口类
 */
class PunchIn extends PunchInModel
{
    
    // 今日签到情况
    public function hasTodayPunchIn($detail = false)
    {
        $has = $this
            ->scope('mid')
            ->where('update_time', '>=', strtotime('today') )
            ->findOrEmpty();

        return $detail ? $has : ( $has->isEmpty() ? 0 : 1 );
    }

    /**
     * 签到
     */
    public function doPunchIn()
    {
        $mid  = request()->mid;
        $user = request()->user;

        // 是否有签到记录
        $record = $this->hasRecord(true);

        if ( $record->isEmpty() ) {

            $re = $this::create([
                'user_id' => $mid,
                'days'    => 1,
            ]);

            if ( !$re->isEmpty() ) {
                // 积分
                $user->credit_key = 'sign_in';
                $user->rel_pk     = $re->id;
                Event::subscribe(CreditEvent::class);
                Event::trigger('AddCredit', $user);
            }

            return $re;

        } else {

            // 今天是否签到
            $today     = $this->hasTodayPunchIn();
            // 昨天是否签到
            $yesterday = $this->hasYesterdayPunchIn(true);

            if ( $today ) throw new LogicException("已签到");
                
            $record->days           = $yesterday->isEmpty() ? 1 : ( $yesterday->days + 1 );
            $record->update_time    = time();

            if ( $record->save() ) {
                // 积分
                $user->credit_key = 'sign_in';
                $user->rel_pk     = $record->id;
                Event::subscribe(CreditEvent::class);
                Event::trigger('AddCredit', $user);
            }

            return $record;
        }
    }

    /**
     * 昨日是否签到
     */
    public function hasYesterdayPunchIn($detail = false)
    {
        $has = $this
            ->scope('mid')
            ->where('update_time', '>=', strtotime('yesterday') )
            ->where('update_time', '<', strtotime('today') )
            ->findOrEmpty();

        return $detail ? $has : ( $has->isEmpty() ? 0 : 1 );
    }

    /**
     * 签到记录
     */
    public function hasRecord($detail = false)
    {
        $has = $this->scope('mid')->findOrEmpty();

        return $detail ? $has : ( $has->isEmpty() ? 0 : 1 );
    }
}
